package com.cdshangpai.photoapp.ui.caseui;

import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.SeekBar;

import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSONObject;
import com.cdshangpai.photoapp.LogConfig;
import com.cdshangpai.photoapp.PhotoAppBaseActivity;
import com.cdshangpai.photoapp.R;
import com.cdshangpai.photoapp.databinding.ActivityVideoPlayBinding;
import com.cdshangpai.utils.db.beans.Video;
import com.cdshangpai.utils.storage.FileInput;
import com.cdshangpai.utils.storage.VideoManage;
import com.cdshangpai.utils.system.ScreenParams;

public class VideoPlayActivity extends PhotoAppBaseActivity {
    ActivityVideoPlayBinding binding;

    VideoManage videoManage;




    private MediaPlayer.OnPreparedListener preparedListener=new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mp.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
                @Override
                public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
                    int mVideoWidth;
                    int mVideoHeight;
                    float scale;
                    int viewWidth=0;
                    int viewHeight=0;

                    mVideoWidth = mp.getVideoWidth();
                    mVideoHeight = mp.getVideoHeight();
                    scale = (float) mVideoWidth / (float) mVideoHeight;
                    float screenScale=(float) ScreenParams.screenWidth/(float)ScreenParams.screenHeight;

                    if(scale==screenScale)
                    {
                        //比例跟屏幕一致
                        viewWidth=ScreenParams.screenWidth;
                        viewHeight=ScreenParams.screenHeight;
                    }
                    if(scale>screenScale)
                    {
                        //视频是宽荧幕,以屏幕宽度为准
                        viewWidth=ScreenParams.screenWidth;
                        Float temp=(float)mVideoHeight/(float)mVideoWidth*(float) viewWidth;
                        viewHeight=temp.intValue();
                    }
                    else
                    {
                        //以屏幕高度为准
                        viewHeight=ScreenParams.screenHeight;
                        Float temp=(float)mVideoWidth/(float)mVideoHeight*(float)viewHeight;
                        viewWidth=temp.intValue();
                    }
                    Log.i(LogConfig.logTag,"播放视图尺寸:width:"+viewWidth+",height:"+viewHeight);

                    LinearLayout.LayoutParams params =(LinearLayout.LayoutParams) binding.videoPlayView.getLayoutParams();
                    params.width=viewWidth;
                    params.height=viewHeight;
                    binding.videoPlayView.setLayoutParams(params);
                }
            });
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        videoManage=new VideoManage();
        binding= DataBindingUtil.setContentView(this,R.layout.activity_video_play);
        binding.setView(this);
        binding.videoPlayView.setOnPreparedListener(preparedListener);

        play();
    }

    private void play()
    {
        String fileName=getVideoName();

        FileInput fileInput=new FileInput(this,null,fileName);
        Integer length=fileInput.getFileLenght();

        if(android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.Q)
        {
            String fullFilename=videoManage.getFullFilename(fileName);
            Log.i(LogConfig.logTag,"加载视频文件："+fullFilename);
            binding.videoPlayView.setVideoPath(fullFilename);
        }
        else {
            Uri uri = videoManage.getUri(fileName);
            binding.videoPlayView.setVideoURI(uri);
        }
        binding.videoPlayView.start();
        startProgressListener();
    }

    private String getVideoName()
    {
        Intent intent=getIntent();
        String param=intent.getStringExtra("param");
        Video video= JSONObject.parseObject(param,Video.class);
        return video.url;
    }

    public void goBack()
    {
        this.finish();
    }

    public void pause()
    {
        binding.videoPlayView.pause();
        binding.setPased(true);
    }

    public void replay()
    {
        binding.videoPlayView.start();
        binding.setPased(false);
        startProgressListener();
    }

    private void startProgressListener()
    {
        new Thread() {
            @Override
            public void run() {
                try {
                    binding.seekBar.setOnSeekBarChangeListener(onSeekBarChangeListener);
                    sleep(500);
//                    Log.i(LogConfig.logTag,"video length:"+binding.videoPlayView.getDuration());
                    binding.seekBar.setMax(binding.videoPlayView.getDuration());
                    while (binding.videoPlayView.isPlaying()) {
                        // 如果正在播放，没0.5.毫秒更新一次进度条
                        int current = binding.videoPlayView.getCurrentPosition();
//                        Log.i(LogConfig.logTag,"play pos:"+current+"/"+binding.seekBar.getMax());
                        VideoPlayActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                binding.seekBar.setProgress(current);
                            }
                        });

                        sleep(200);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private SeekBar.OnSeekBarChangeListener onSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
        // 当进度条停止修改的时候触发
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // 取得当前进度条的刻度
            int progress = seekBar.getProgress();
            if (binding.videoPlayView.isPlaying()) {
                // 设置当前播放的位置
                binding.videoPlayView.seekTo(progress);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {

        }
    };
}